package learn.linkedlist;

public class Jusepfu {
}

class CircleSingleLinkedList {
    private Boy first = new Boy(-1);

    /**
     * @param nums 节点个数
     */
    public void addBoy(int nums) {
        validate(nums);
        Boy curBoy = null;//辅助指针
        for (int i = 1; i <= nums; i++) {
            Boy boy = new Boy(i);
            if (i == 1) {
                first = boy;
                first.setNext(first);
                curBoy = first;
            } else {
                curBoy.setNext(boy);
                curBoy = boy;
                curBoy.setNext(first);
            }
        }
    }

    public void show() {
        if (first.getNo() == -1) {
            System.out.println("链表为空");
            return;
        }
        Boy curBoy = first;
        do {
            System.out.println(curBoy.getNo());
            curBoy = curBoy.getNext();
        } while (curBoy != first);
    }

    public void countBoys(int k, int m, int num) {
        if (first.getNo() == -1 || first.getNext() == null || k == 0 || k > num) {
            System.out.println("参数不合法");
            return;
        }
        Boy preNode = first.getNext();
        while (preNode.getNext() != first) {//遍历到最后
            preNode = preNode.getNext();
        }
        for (int i = 0; i < k - 1; i++) {//将指针指向对应的起始节点
            first = first.getNext();
            preNode = preNode.getNext();
        }
        while (first.getNext() != first) {//自己指向自己，环形链表中只有一个节点
            for (int i = 0; i < m - 1; i++) {//移动指针m-1次，first指针指向的节点就是要删除的节点
                first = first.getNext();
                preNode = preNode.getNext();
            }
            System.out.printf("被删除的节点为%d\n", first.getNo());
            preNode.setNext(first.getNext());
            first = first.getNext();
        }
        System.out.printf("最后的节点为%d\n", first.getNo());
    }


    private void validate(int nums) {
        if (nums < 1) {
            System.out.println("参数不合法");
            return;
        }
    }
}

class Boy {
    private int no;
    private Boy next;

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
}
